package com.tools.project.demo;


import at.syntaxerror.json5.JSONArray;
import at.syntaxerror.json5.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by 2025/5/27
 *
 * @author ldh
 * @version V1.0
 * @description: 待补充...
 */
public class GitLabFileFetcherUtil {


    private static final Map<String, String> projectIdMap = new HashMap<>();
    private static final Map<String, String> projectTokenMap = new HashMap<>();
    private static final Map<String, String> envTokenMap = new HashMap<>();
    private static final Map<String, String> envExeMapBody = new HashMap<>();
    private static final Map<String, String> envExeMapHead = new HashMap<>();
    private static final Map<String, String> envPreUrlMap = new HashMap<>();
    static {
        // 项目id
        projectIdMap.put("zztx_dh_pc", "124");
        projectIdMap.put("billservice", "148");
        projectIdMap.put("customerservice", "137");
        projectIdMap.put("financeservice", "342");
        projectIdMap.put("goodsservice", "120");
        projectIdMap.put("imexportservice", "340");
        projectIdMap.put("saassystemsetting", "247");
        projectIdMap.put("StatisticsService", "222");
        projectIdMap.put("zztx_crm_pc", "126");
        projectIdMap.put("zztx_ms_pc", "360");
        projectIdMap.put("web-platform", "119");
        projectIdMap.put("supplierservice", "384");

        // 项目token
        projectTokenMap.put("zztx_dh_pc", "H3nS2pqK7PhnSC5VGyy9");
        projectTokenMap.put("billservice", "Ydw-dyNASgDPygeu7mgc");
        projectTokenMap.put("customerservice", "fDgyZtxVHJsANQp1wbZo");
        projectTokenMap.put("financeservice", "YHvE79tQ5mKvxayqwMzR");
        projectTokenMap.put("goodsservice", "gCyeFzto4hoRNUrECVRd");
        projectTokenMap.put("imexportservice", "cPFp2gp_ejYHWwX6-K2Z");
        projectTokenMap.put("saassystemsetting", "tc5ZsE93Vh2xETi9CV-j");
        projectTokenMap.put("StatisticsService", "K5WgE-_MMTArPgcFgkLH");
        projectTokenMap.put("zztx_crm_pc", "egvpU4hyoTmDyVZDYUn8");
        projectTokenMap.put("zztx_ms_pc", "zGWe_T4NiwiUtsR96RkL");
        projectTokenMap.put("web-platform", "9f7ngZcPjGErzqX9_29h");
        projectTokenMap.put("supplierservice", "mQn_LKGeyDdB3suARa5-");

        //环境前缀地址
        envPreUrlMap.put("dev", "https://dev-hdsaas.facehand.cn/gateway");
        envPreUrlMap.put("fat", "https://fat-hdsaas.facehand.cn/gateway");
        envPreUrlMap.put("pre", "https://pre-hdsaas.facehand.cn/gateway");
        envPreUrlMap.put("pre_temp", "https://pre-hdsaas.facehand.cn/gateway");
        envPreUrlMap.put("uat", "https://c.handday.com/gateway");
        envPreUrlMap.put("prod", "https://c.handday.com/gateway");

        //token获取地址
        envTokenMap.put("dev", envPreUrlMap.get("dev")+"/oauth-service/oauth/token?wxCorpId=wpc7diCwAAI0KNCMvlAbcB4xslzyzS8Q&wxUserId=woc7diCwAAyoPU6R59iAwE_UGz6Vrjfw&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000000");
        envTokenMap.put("fat", envPreUrlMap.get("fat")+"/oauth-service/oauth/token?wxCorpId=wpc7diCwAAiaTTafQCtv7InNcTHq3IJQ&wxUserId=woc7diCwAARFkcBBSPX8uL8rRHag4V8g&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150007745");
        envTokenMap.put("pre", envPreUrlMap.get("pre")+"/oauth-service/oauth/token?wxCorpId=wpc7diCwAAiaTTafQCtv7InNcTHq3IJQ&wxUserId=woc7diCwAARFkcBBSPX8uL8rRHag4V8g&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000022");
        envTokenMap.put("pre_temp", envPreUrlMap.get("pre_temp")+"/oauth-service/oauth/token?wxCorpId=wpc7diCwAAiaTTafQCtv7InNcTHq3IJQ&wxUserId=woc7diCwAARFkcBBSPX8uL8rRHag4V8g&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000022");
        envTokenMap.put("uat", envPreUrlMap.get("uat")+"/oauth-service/oauth/token?wxCorpId=wppVVJEQAAaLJvawFRJrqFJwH3ZxzHGw&wxUserId=wopVVJEQAA98nZMkA0I8OLMtrP-F9t8A&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000010");
        envTokenMap.put("prod", envPreUrlMap.get("prod")+"/oauth-service/oauth/token?wxCorpId=wppVVJEQAAaLJvawFRJrqFJwH3ZxzHGw&wxUserId=wopVVJEQAA98nZMkA0I8OLMtrP-F9t8A&grant_type=work_wx_authentication&client_id=40087685617893436&client_secret=40087685617893436&corpId=150000010");
        //执行接口
        //动态表头
        envExeMapHead.put("saveHeadUrl", "/systemsetting/api/v1/searchField/saveCategoryConfig");
        envExeMapHead.put("queryHeadUrl", "/systemsetting/api/v1/searchField/queryDefaultConfig");

        //列配置
        envExeMapBody.put("saveBodyUrl", "/goodsservice/api/v1/system/field/batchUpdate");
        envExeMapBody.put("queryBodyUrl", "/goodsservice/api/v1/setting/filed/list");
    }

    private static String getProjectId(String url) {
        for (Map.Entry<String, String> entry : projectIdMap.entrySet()) {
            if (url.contains(entry.getKey())) {
                return entry.getValue();
            }
        }
        throw new RuntimeException("未查询到项目id");
    }

    private static String getProjectToken(String url) {
        for (Map.Entry<String, String> entry : projectTokenMap.entrySet()) {
            if (url.contains(entry.getKey())) {
                return entry.getValue();
            }
        }
        throw new RuntimeException("未查询到项目Token");
    }

    private static String getBranch(String url) {
        int startIndex = url.indexOf("/blob/") + "/blob/".length();
        int endIndex = url.indexOf("/src");
        return url.substring(startIndex, endIndex);
    }

    private static String getFilepath(String url) {
        int startIndex = url.indexOf("src/");
        return url.substring(startIndex);
    }

    private static Boolean isBodyField(String url) {
        return !url.contains("front-end");
    }

    /**
     * 转换Json
     * @author ldh
     * @date 2025-06-13 17:41
     * @param url
     * @param inputBranch
     * @param version
     */
    public static String convert(String url, String inputBranch, String version) {

        String projectId = null;
        String branch = null;
        String filepath = null;
        // 替换为你的 GitLab Personal Access Token
        String token = null;
        try {
            if (StringUtils.isBlank(url)) {
                return "请输入需要转换的数据";
            }

            if (StringUtils.isBlank(version)) {
                return "请输入字段版本号";
            }

            // 获取项目id
            projectId = getProjectId(url);

            // 获取token
            token = getProjectToken(url);

            // 获取文件路径
            filepath = getFilepath(url);

            // 获取执行分支
            if (isBodyField(url)) {
                // 表体
                branch = getBranch(url);
            } else {
                // 表头
                branch = inputBranch;
            }

            if (StringUtils.isBlank(inputBranch)) {
                return "请输入执行分支";
            }
            String configContent = getConfigContent(projectId, branch, filepath, token);

            if (isBodyField(url)) {
                JSONArray jsonArray = new JSONArray(configContent);

                for (Object o : jsonArray) {
                    JSONObject jsonObject = (JSONObject) o;
                    Object fieldVersion = jsonObject.get("fieldVersion");
                    if (fieldVersion == null) {
                        throw new RuntimeException("未查询到配置中的 fieldVersion 字段");
                    } else {
                        jsonObject.set("fieldVersion", version);
                    }
                }
                return jsonArray.toString();

            } else {
                JSONObject jsonObject = new JSONObject(configContent);
                Object fieldVersion = jsonObject.get("version");
                if (fieldVersion == null) {
                    throw new RuntimeException("未查询到配置中的 version 字段");
                } else {
                    jsonObject.set("version", version);
                }
                return jsonObject.toString();
            }
        } catch (Exception e) {
            return e.getMessage();
        }

    }

    /**
     * 获取代码
     * @author ldh
     * @date 2025-06-13 17:41
     * @param projectId
     * @param branch
     * @param filepath
     * @param token
     */
    private static String getConfigContent(String projectId, String branch, String filepath, String token) {

        try {
            String decode = URLDecoder.decode(filepath, StandardCharsets.UTF_8);
            String encodedString = URLEncoder.encode(decode, StandardCharsets.UTF_8);
            String apiUrl = String.format(
                    "https://gitlab.facehand.cn/api/v4/projects/%s/repository/files/%s?ref=%s",
                    projectId, encodedString, branch
            );


            // 创建 HTTP 连接
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("PRIVATE-TOKEN", token);
            conn.setRequestMethod("GET");

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 输出文件内容
            System.out.println("文件内容:\n" + response.toString());
            JSONObject jsonObject = new JSONObject(response.toString());
            String content = jsonObject.get("content").toString();

            // 解码 Base64 字符串为字节数组
            byte[] decodedBytes = Base64.getDecoder().decode(content);

            // 将字节数组转换为字符串

            return new String(decodedBytes, StandardCharsets.UTF_8);


        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    /**
     * 获取请求接口的token
     *
     * @param env
     * @author ldh
     * @date 2025-06-13 15:33
     */
    public static String getToken(String env) {
        String token = OkHttpUtil.postFormParams(envTokenMap.get(env), null);
        if (StringUtils.isBlank(token)) {
            return "";
        }
        JSONObject jsonObject = new JSONObject(token);
        return jsonObject.getObject("data")
                .getString("access_token");
    }

    /**
     * 执行接口（动态表头和列配置）
     *
     * @param url
     * @param env
     * @param token
     * @param content
     * @author ldh
     * @date 2025-06-13 15:47
     */
    public static String submit(String url, String env, String token, String content,boolean isUat) {
        try {
            String exeUrl = "";
            String rst = "";
            if (isBodyField(url)) {
                exeUrl = envPreUrlMap.get(env) + envExeMapBody.get("saveBodyUrl");
            } else {
                exeUrl = envPreUrlMap.get(env) + envExeMapHead.get("saveHeadUrl");
            }
            if (StringUtils.isBlank(exeUrl)) {
                rst = "接口地址为空";
                return rst;
            }
            if (StringUtils.isBlank(token)) {
                rst = "token为空";
                return rst;
            }
            if (StringUtils.isBlank(content)) {
                rst = "内容为空";
                return rst;
            }
            rst = OkHttpUtil.postJsonParams(exeUrl, content, token, isUat);
            System.out.println("执行结果:\n" + rst);
            return rst;
        } catch (Exception ex) {
            return String.format("执行失败：%s", ex);
        }
    }

    /**
     *查询接口（动态表头和列配置）
     *
     * @param url
     * @param env
     * @param token
     * @param content
     * @author ldh
     * @date 2025-06-13 15:47
     */
    public static String query(String url, String env, String token, String content,boolean isUat) {
        try {
            String exeUrl = "";
            String rst = "";
            if (StringUtils.isBlank(token)) {
                rst = "token为空";
                return rst;
            }
            if (StringUtils.isBlank(content)) {
                rst = "内容为空";
                return rst;
            }
            if (isBodyField(url)) {
                JSONArray jsonArray = new JSONArray(content);
                JSONObject jsonObject = jsonArray.getObject(0);
                exeUrl = envPreUrlMap.get(env) + envExeMapBody.get("queryBodyUrl");
                Map<String, String> queries = new HashMap<>();
                queries.put("isReset", "true");
                queries.put("businessType", jsonObject.get("businessType").toString());
                rst = OkHttpUtil.get(exeUrl, queries, token);
            } else {
                JSONObject jsonObject = new JSONObject(content);
                String categoryKey = jsonObject.get("categoryKey").toString();
                exeUrl = envPreUrlMap.get(env) + envExeMapHead.get("queryHeadUrl");
                String body = "{\"categoryKey\":\"" + categoryKey + "\"}";
                rst = OkHttpUtil.postJsonParams(exeUrl, body, token, isUat);
            }
            System.out.println("执行结果:\n" + rst);
            return rst;
        } catch (Exception ex) {
            return String.format("执行失败：%s", ex);
        }
    }
}
